/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dbFish;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mesias
 */
public class SimpleConnector {
	/**
	 * Database URI. <p>
	 */
	private String uri = "jdbc:postgresql://localhost/";
	//	private String uri = "jdbc:hsqldb:hsql://localhost/";

	/**
	 * The database name. <p>
	 */
	private String database = "teste";

	/**
	 * The database user. <p>
	 */
	private String user = "tomcat4";

	/**
	 * Password to the database. <p>
	 */
	private String password = "";

	/**
	 * The JDBC connection pool. <p>
	 */
	private Connection connection = null;
//	private LinkedList<Connection> borrowedPool = null;
        protected static Logger logger = Logger.getLogger("dbFish");


	public SimpleConnector(String uri, String database, String user, String password) {
		super();
		this.uri = uri;
		this.database = database;
		this.user = user;
		this.password = password;
	}

	public synchronized Connection getConnection() throws SQLException{
		if (connection==null) {
			connection = createConnection();
		}
		//logger.debug("GETTING NEW CONNECTION: OK");
		return connection;
	}


	private boolean isValid(Connection con){
		if (con==null) return false;
		try {
			if (con.isClosed()){
				con.close();
				return false;
			}
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	private Connection createConnection() throws SQLException{
		//logger.info("CREATING NEW CONNECTION  --> Database: " + uri + database + " user:" + user);
		return DriverManager.getConnection(uri+database, user, password);
	}


	public synchronized void closeConnection(){
		if (connection==null) return;
		try{
			connection.close();
                        connection = null;
			logger.info("Conexion Closed...");
		} catch (Exception sqle) {
			logger.log(Level.OFF,"Exception closing connection...");
		}
	}
	public synchronized void shutdown() {
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	};


	public synchronized void closeConnection(Connection connection){
		if (connection==null) return;
		try{
			connection.close();
			logger.info("Conexion Closed...");
		} catch (Exception sqle) {
			logger.log(Level.OFF, "Exception closing connection...");
		}
	}
}
